package com.studyjava.guessdx;

import android.content.DialogInterface;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Xml;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlSerializer;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class guessname extends AppCompatActivity {
    private ImageView imageView;
    private TextView textView;
    private EditText editText;
    private Button buttonSubmit;
    private TextView textViewScore;

    private List<StringID> stringIDList = new ArrayList<>();
    private StringID currentStringID;
    private int userScore = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.guess_name);

        imageView = findViewById(R.id.imageView);
        textView = findViewById(R.id.textView);
        editText = findViewById(R.id.editText);
        buttonSubmit = findViewById(R.id.buttonSubmit);
        textViewScore = findViewById(R.id.textViewScore);

        // 初始化跳过按钮和别名按钮
        Button buttonSkip = findViewById(R.id.buttonSkip);
        Button buttonAddAlias = findViewById(R.id.buttonAddAlias);

        File aliasFile = new File(getFilesDir(), "Alias.xml");
        if (!aliasFile.exists()) {
            copyAliasXMLFromAssets();
        }

        // 跳过当前题目按钮
        buttonSkip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                randomizeStringID();  // 直接跳到下一个题目
            }
        });

        // 添加别名按钮
        buttonAddAlias.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (currentStringID != null) {
                    showAddAliasDialog();
                } else {
                    Toast.makeText(guessname.this, "当前没有可添加别名的ID", Toast.LENGTH_SHORT).show();
                }
            }
        });

        // 解析XML
        parseXML();

        //初始化积分
        loadUserScore();

        updateScoreDisplay();

        // 随机抽取一个stringID
        randomizeStringID();

        // 提交按钮点击事件
        buttonSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkInput();
            }
        });
    }

    private void updateScoreDisplay() {
        textViewScore.setText("当前积分: " + userScore);
    }

    private void copyAliasXMLFromAssets() {
        try {
            InputStream inputStream = getAssets().open("Alias.xml");
            OutputStream outputStream = openFileOutput("Alias.xml", MODE_PRIVATE);
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            outputStream.close();
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "无法复制 Alias.xml", Toast.LENGTH_SHORT).show();
        }
    }

    // 从 userdata.xml 加载用户积分
    private void loadUserScore() {
        try {
            InputStream inputStream = openFileInput("userdata.xml");
            XmlPullParser parser = Xml.newPullParser();
            parser.setInput(inputStream, "UTF-8");

            int eventType = parser.getEventType();
            while (eventType != XmlPullParser.END_DOCUMENT) {
                String tagName = parser.getName();
                if (eventType == XmlPullParser.START_TAG && "Score".equals(tagName)) {
                    userScore = Integer.parseInt(parser.nextText());
                }
                eventType = parser.next();
            }
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 将用户积分保存到 userdata.xml
    private void saveUserScore() {
        try {
            FileOutputStream fileOutputStream = openFileOutput("userdata.xml", MODE_PRIVATE);
            XmlSerializer serializer = Xml.newSerializer();
            serializer.setOutput(fileOutputStream, "UTF-8");

            serializer.startDocument("UTF-8", true);
            serializer.startTag(null, "UserData");

            serializer.startTag(null, "Score");
            serializer.text(String.valueOf(userScore));
            serializer.endTag(null, "Score");

            serializer.endTag(null, "UserData");
            serializer.endDocument();
            fileOutputStream.close();
            updateScoreDisplay();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    // 解析MusicSort.xml
    private void parseXML() {
        try {
            InputStream inputStream = getAssets().open("MusicSort.xml");
            XmlPullParser parser = Xml.newPullParser();
            parser.setInput(inputStream, "UTF-8");

            int eventType = parser.getEventType();
            StringID stringID = null;

            while (eventType != XmlPullParser.END_DOCUMENT) {
                String tagName = parser.getName();

                if (eventType == XmlPullParser.START_TAG) {
                    if ("StringID".equals(tagName)) {
                        stringID = new StringID();
                    } else if (stringID != null) {
                        if ("id".equals(tagName)) {
                            stringID.setId(Integer.parseInt(parser.nextText()));
                        } else if ("str".equals(tagName)) {
                            stringID.setStr(parser.nextText());
                        }
                    }
                } else if (eventType == XmlPullParser.END_TAG) {
                    if ("StringID".equals(tagName) && stringID != null) {
                        stringIDList.add(stringID);
                    }
                }
                eventType = parser.next();
            }
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 随机抽取一个stringID
    private void randomizeStringID() {
        if (!stringIDList.isEmpty()) {
            Random random = new Random();
            currentStringID = stringIDList.get(random.nextInt(stringIDList.size()));

            // 显示ID
            textView.setText("ID: " + currentStringID.getId());

            // 检查ID位数并处理5位数的特殊情况
            int id = currentStringID.getId();
            String formattedId;

            if (id >= 10000 && id < 100000) {
                // 5位数的情况，减去10000再补0
                formattedId = String.format("%06d", id - 10000);
            } else {
                // 其他位数正常补0
                formattedId = String.format("%06d", id);
            }

            // 显示对应的图片，调用修正的文件路径
            loadImageFromAssets("music_pic/UI_Jacket_" + formattedId + ".png");
        }
    }

    // 从 assets 目录中加载图片
    private void loadImageFromAssets(String filePath) {
        try {
            AssetManager assetManager = getAssets();
            InputStream inputStream = assetManager.open(filePath);
            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
            imageView.setImageBitmap(bitmap);
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(guessname.this, "无法加载图片：" + filePath, Toast.LENGTH_SHORT).show();
        }
    }

    // 检查输入框的内容是否等于str或别名（支持模糊匹配）
    private void checkInput() {
        String input = editText.getText().toString().trim();

        if (currentStringID != null) {
            // 获取正确答案并去除标点符号和大小写差异
            String correctAnswer = removePunctuation(currentStringID.getStr()).toLowerCase();
            String userAnswer = removePunctuation(input).toLowerCase();

            // 检查用户输入是否与正确答案匹配（忽略大小写和标点符号）
            if (userAnswer.equals(correctAnswer) || isAliasMatch(currentStringID.getId(), userAnswer)) {
                Toast.makeText(guessname.this, "正确！继续下一个", Toast.LENGTH_SHORT).show();
                userScore += 10; // 答对加10分
                saveUserScore(); // 保存积分
                randomizeStringID();
                editText.setText("");  // 清空输入框
            } else {
                Toast.makeText(guessname.this, "输入错误，请重试", Toast.LENGTH_SHORT).show();
                userScore -= 2; // 答错减2分
                saveUserScore(); // 保存积分
            }
        }
    }


    // 去除标点符号的方法
    private String removePunctuation(String input) {
        return input.replaceAll("[\\p{Punct}\\s]", "");  // 去除标点和空格
    }

    private boolean isAliasMatch(int id, String userInput) {
        try {
            // 从内部存储中加载 Alias.xml
            InputStream inputStream = openFileInput("Alias.xml");
            XmlPullParser parser = Xml.newPullParser();
            parser.setInput(inputStream, "UTF-8");

            int eventType = parser.getEventType();
            boolean isCurrentId = false;

            while (eventType != XmlPullParser.END_DOCUMENT) {
                String tagName = parser.getName();

                if (eventType == XmlPullParser.START_TAG) {
                    if ("StringID".equals(tagName)) {
                        // 修改：检查下一个标签是否是 id
                        eventType = parser.next();
                        if (eventType == XmlPullParser.START_TAG && "id".equals(parser.getName())) {
                            int aliasId = Integer.parseInt(parser.nextText());
                            isCurrentId = (aliasId == id);  // 检查是否是当前的ID
                        }
                    } else if (isCurrentId && "alias".equals(tagName)) {
                        // 获取别名并与用户输入比较（忽略大小写和标点符号）
                        String alias = removePunctuation(parser.nextText()).toLowerCase();
                        if (userInput.equals(alias)) {
                            inputStream.close();
                            return true;  // 如果匹配则返回true
                        }
                    }
                } else if (eventType == XmlPullParser.END_TAG) {
                    if ("StringID".equals(tagName)) {
                        isCurrentId = false;  // 结束当前ID的处理
                    }
                }
                eventType = parser.next();
            }

            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    // 显示添加别名的对话框
    private void showAddAliasDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("添加别名");

        // 为对话框设置输入框
        final EditText input = new EditText(this);
        input.setHint("请输入别名");
        builder.setView(input);

        // 设置确认按钮
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String alias = input.getText().toString().trim();
                if (!alias.isEmpty()) {
                    addAliasToXML(currentStringID.getId(), alias);
                } else {
                    Toast.makeText(guessname.this, "别名不能为空", Toast.LENGTH_SHORT).show();
                }
            }
        });

        // 设置取消按钮
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        // 显示对话框
        builder.show();
    }

    // 将别名添加到 Alias.xml
    private void addAliasToXML(int id, String alias) {
        try {
            // 读取现有的别名数据
            File aliasFile = new File(getFilesDir(), "Alias.xml");
            if (!aliasFile.exists()) {
                copyAliasXMLFromAssets(); // 如果文件不存在，则重新复制
            }

            InputStream inputStream = openFileInput("Alias.xml");
            XmlPullParser parser = Xml.newPullParser();
            parser.setInput(inputStream, "UTF-8");

            List<AliasEntry> aliasEntries = new ArrayList<>();
            AliasEntry currentAliasEntry = null;

            int eventType = parser.getEventType();
            while (eventType != XmlPullParser.END_DOCUMENT) {
                String tagName = parser.getName();

                if (eventType == XmlPullParser.START_TAG) {
                    if ("StringID".equals(tagName)) {
                        currentAliasEntry = new AliasEntry();
                    } else if ("id".equals(tagName)) {
                        if (currentAliasEntry != null) {
                            currentAliasEntry.id = Integer.parseInt(parser.nextText());
                        }
                    } else if ("alias".equals(tagName)) {
                        if (currentAliasEntry != null) {
                            currentAliasEntry.aliases.add(parser.nextText());
                        }
                    }
                } else if ( eventType == XmlPullParser.END_TAG) {
                    if ("StringID".equals(tagName) && currentAliasEntry != null) {
                        aliasEntries.add(currentAliasEntry);
                        currentAliasEntry = null;
                    }
                }
                eventType = parser.next();
            }
            inputStream.close();

            // 添加新别名
            boolean aliasAdded = false;
            for (AliasEntry entry : aliasEntries) {
                if (entry.id == id) {
                    if (!entry.aliases.contains(alias)) {
                        entry.aliases.add(alias);
                        aliasAdded = true;
                    }
                    break;
                }
            }

            if (!aliasAdded) {
                // 如果当前ID不存在，则添加新条目
                AliasEntry newEntry = new AliasEntry();
                newEntry.id = id;
                newEntry.aliases.add(alias);
                aliasEntries.add(newEntry);
            }

            // 将修改后的数据写回Alias.xml
            FileOutputStream fileOutputStream = openFileOutput("Alias.xml", MODE_PRIVATE);
            XmlSerializer serializer = Xml.newSerializer();
            serializer.setOutput(fileOutputStream, "UTF-8");

            serializer.startDocument("UTF-8", true);
            serializer.startTag(null, "Aliases");

            for (AliasEntry entry : aliasEntries) {
                serializer.startTag(null, "StringID");

                serializer.startTag(null, "id");
                serializer.text(String.valueOf(entry.id));
                serializer.endTag(null, "id");

                for (String a : entry.aliases) {
                    serializer.startTag(null, "alias");
                    serializer.text(a);
                    serializer.endTag(null, "alias");
                }

                serializer.endTag(null, "StringID");
            }

            serializer.endTag(null, "Aliases");
            serializer.endDocument();
            fileOutputStream.close();

            // 更新积分
            userScore += 3;
            saveUserScore();
            Toast.makeText(guessname.this, "别名已成功添加", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(guessname.this, "无法添加别名", Toast.LENGTH_SHORT).show();
        }
    }

    // 定义别名条目类
    private static class AliasEntry {
        int id;
        List<String> aliases = new ArrayList<>();
    }

    // 定义一个StringID类
    private static class StringID {
        private int id;
        private String str;

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getStr() {
            return str;
        }

        public void setStr(String str) {
            this.str = str;
        }
    }
}
